<template>
  <el-card shadow="hover">
    <el-button
      type="primary"
      :icon="Plus"
      @click="TrademarkDiaLo({ id: 0, tmName: '', logoUrl: '' })">
      添加品牌
    </el-button>

    <el-table
      :data="records"
      border
      class="trademark__table"
      v-loading="loading">
      <el-table-column label="序号" width="80" type="index" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌Logo">
        <template #default="{ row }">
          <el-image :src="row.logoUrl" class="table__img" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="TrademarkDiaLo(row)">
          </el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="DelTrademark(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout=" prev, pager, next, jumper, ->, total, sizes"
      :total="total"
      @size-change="getTradeMarkList"
      @current-change="getTradeMarkList" />

    <el-dialog
      v-model="dialogFormVisible"
      :title="`${formData.id ? '修改' : '添加'}品牌`">
      <el-form
        label-width="100px"
        ref="formRef"
        :model="formData"
        :rules="formRules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            class="trademark__inp"
            placeholder="请输入品牌名称"
            v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.png,.gif">
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "JTrademark",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";

import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";
import {
  getTradeMarkListApi,
  addTradeMarkApi,
  updateTradeMarkApi,
  delTradeMarkApi,
} from "@/api/product/trademark";

/************************ 删除品牌模块 ********************************* */
// 删除按钮
const DelTrademark = ({ id, tmName }: TrademarkItem) => {
  ElMessageBox.confirm(`确定要删除 ${tmName} 吗？`, "删除品牌", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delTradeMarkApi(id);
      ElMessage({
        type: "success",
        message: "删除品牌成功~~~",
      });
      getTradeMarkList();
    })
    .catch(() => {
      // 不用写
    });
};

/************************ 添加修改删除品牌模块 ********************************* */
const BASE_URL = import.meta.env.VITE_API_URL;
const dialogFormVisible = ref(false); // 控制模态框是否展示
const formRef = ref(); // 获取表单实例
const formData = reactive({
  id: 0,
  tmName: "",
  logoUrl: "",
}); // 定义数据

// 合并的修改和添加的按钮
const TrademarkDiaLo = (row: TrademarkItem) => {
  formData.tmName = row.tmName;
  formData.logoUrl = row.logoUrl;
  formData.id = row.id;

  // 清除表单验证提示
  formRef.value?.clearValidate();
  dialogFormVisible.value = true;
};

// 文件上传成功时的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // response 是服务器响应回来的数据
  formData.logoUrl = response.data;
  formRef.value.clearValidate(["logoUrl"]);
};

// 定义表单规则  数据要和规则name一样
const formRules = reactive({
  tmName: [
    { required: true, message: "请输入品牌内容", trigger: "blur" },
    { min: 2, max: 20, message: "品牌名称长度2-10位", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "请选择品牌图片" }],
});

// 上传文件之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileTypes = ["image/jpeg", "image/png", "image/gif"];
  // 不是上述的图片类型就提示错误
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error("上传图片只能是jpg或png格式!");
    // 返回false 上传失败 不会上传
    return false;
  } else if (rawFile.size / 1024 > 2000) {
    ElMessage.error("图片大小不能超过200kb!");
    return false;
  }
  return true;
};

// 提交表单
const submit = async () => {
  // 对整个表单进行验证
  await formRef.value.validate();

  if (formData.id) {
    // 发送修改品牌参数
    await updateTradeMarkApi(formData);
  } else {
    // 发送添加请求
    await addTradeMarkApi(formData);
  }
  dialogFormVisible.value = false; // 关闭模态框
  ElMessage.success(`${formData.id ? "修改" : "添加"}品牌成功~~~~~`);
  // 重新获取数据展示
  getTradeMarkList();
};

/************************ 分页器&数据展示 ********************************* */
const currentPage = ref(1); //当前页
const pageSize = ref(3); //一页展示多少个
const total = ref(0); //总页数
const loading = ref(false);

const records = ref<TrademarkList>([]); //请求过来的数据展示

// 封装发送获取列表的函数
const getTradeMarkList = async () => {
  loading.value = true;
  const res = await getTradeMarkListApi(currentPage.value, pageSize.value);
  records.value = res.records;
  total.value = res.total;
  loading.value = false;
};

// 挂载调用获取列表函数
onMounted(getTradeMarkList);
</script>

<style scoped lang="scss">
.trademark__table {
  margin: 20px 0;
}
.table__img {
  width: 100px;
  height: 60px;
}
.avatar-uploader {
  :deep() {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.trademark__inp {
  width: 350px;
}
</style>
